package cn.itcast.service.impl;

import cn.itcast.dao.RoleDao;
import cn.itcast.dao.UserDao;
import cn.itcast.entity.PageResult;
import cn.itcast.entity.QueryPageBean;
import cn.itcast.pojo.Menu;
import cn.itcast.pojo.Role;
import cn.itcast.pojo.User;
import cn.itcast.service.UserService;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    //根据用户名查询密码(登录功能)

    @Autowired
    private RoleDao roleDao;
    @Override
    public User Login(String username) {
        User user = userDao.Login(username);
        return user;
    }

    @Override
    public PageResult findByPage(QueryPageBean queryPageBean) {
        //开启分页查询
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //根据条件分页查询检查项信息
        Page<User> page = userDao.findAll();
        //构建分页数据返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public List<Role> findAllRole() {
        return roleDao.findAllRole();
    }

    @Transactional
    @Override
    public void insert(User user, Integer[] roleIds) {
        userDao.insert(user);
        Integer id=  user.getId();
        userDao.addRole(id,roleIds);
        //userDao.deleteAllRole(id);
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public void update(User user, Integer[] roleIds) {
        userDao.update(user);
        userDao.removeAllRole(user.getId());
        if (roleIds!=null&&roleIds.length>0){
            userDao.addRole(user.getId(),roleIds);
        }
    }

    @Override
    public Integer[] findRoleById(Integer id) {
        Integer[] ids = userDao.findRoleById(id);

        return ids;
    }
    @Transactional
    @Override
    public void deleteById(Integer id) {
        userDao.deleteRoleByUserId(id);
        userDao.deleteById(id);

    }

    @Override
    public List<Menu> getMenu (String username){
        List<Menu> menuList = userDao.findMenu(username);
        menuList.stream().forEach(menu -> {
            List<Menu> childrenMenu = userDao.findChildrenMenu(menu.getId(), username);
            menu.setChildren(childrenMenu);
        });
        return menuList;
    }

}
